import 'dotenv/config';
import "reflect-metadata";
import Koa from "koa";
import KoaLogger from 'koa-logger';
import bodyParser from "koa-bodyparser";
import { useKoaServer } from "routing-controllers";
import { AppDataSource } from "./database";
import { router, swagger } from './controllers';
import { getAuthorizationChecker } from './common/CommonUtils';

const { HOST = 'localhost', PORT = 3000 } = process.env;

const app = new Koa();

app
  .use(bodyParser())
  .use(KoaLogger())
  .use(swagger({ exposeSpec: true }))

useKoaServer(app, {
  ...router,
  cors: true,
  authorizationChecker: async action =>
    !!(await getAuthorizationChecker(action)),
  currentUserChecker: getAuthorizationChecker
});

console.time('Server boot');
AppDataSource.initialize()
  .then(() => {
    console.log("DataSource has been initialized!");

    app.listen(PORT, () => {
      console.log(`Server running at http://${HOST}:${PORT}`);
      console.log(`Swagger API served at http://${HOST}:${PORT}/docs/`);
      console.timeEnd('Server boot');
    });

  })
  .catch((error) => console.log(error));